package com.sita.tboard.hitchhike.running;

import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.sita.bike.R;
import com.sita.bike.support.GlobalContext;
import com.sita.tboard.hitchhike.HitchhikeConstants;
import com.sita.tboard.hitchhike.bean.TicketModel;
import com.sita.tboard.hitchhike.detail.PassengerTripDetailActivity;
import com.sita.tboard.hitchhike.event.HitchhikePassengerReloadEvent;
import com.sita.tboard.hitchhike.event.HitchhikePassengerTripPayEvent;
import com.sita.tboard.hitchhike.helper.HitchhikeNetworkHelper;
import com.sita.tboard.hitchhike.helper.HitchhikePersistHelper;
import com.sita.tboard.hitchhike.history.PassengerHistoryTicketsActivity;
import com.sita.tboard.hitchhike.listeners.OnGetTicketsListener;
import com.sita.tboard.hitchhike.listeners.OnPayHitchhikeListener;
import com.sita.tboard.hitchhike.publish.PassengerPublishTripActivity;
import com.sita.tboard.view.MyDividerItemDecoration;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import de.greenrobot.event.EventBus;

public class PassengerRunningTripsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, SwipeRefreshLayout.OnRefreshListener, OnMoreListener {

    @Bind(R.id.ticket_list)
    SuperRecyclerView listView;

    @Bind(R.id.btn_new_trip)
    Button btnNewTrip;

    private LoaderManager.LoaderCallbacks loaderCallbacks;
    private PassengerRunningTripsAdapter mAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private int currPage = 0;

    private static class PassengerCursorLoader extends CursorLoader {

        public PassengerCursorLoader(Context context) {
            super(context);
        }

        @Override
        public Cursor loadInBackground() {
            return HitchhikePersistHelper.INSTANCE.openPassengerTicketUnfinishedCursor();
        }
    }

    public PassengerRunningTripsFragment() {
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        PassengerCursorLoader cursorLoader = new PassengerCursorLoader(getContext());
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (mAdapter == null) {
            mAdapter = new PassengerRunningTripsAdapter(getContext(), data);
            listView.setAdapter(mAdapter);
        } else {
            mAdapter.swapCursor(data);
        }
        setupButtons();
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }

    @SuppressWarnings("unused")
    public static PassengerRunningTripsFragment newInstance() {
        PassengerRunningTripsFragment fragment = new PassengerRunningTripsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loaderCallbacks = this;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hitchhike_passenger_running, container, false);
        ButterKnife.bind(this, view);

        mLinearLayoutManager = new LinearLayoutManager(getActivity());
        listView.setLayoutManager(mLinearLayoutManager);
        Drawable drawable = new ColorDrawable(getResources().getColor(R.color.divider_list));
        listView.addItemDecoration(new MyDividerItemDecoration(drawable, true, true));

        listView.setOnMoreListener(this);
        listView.setRefreshListener(this);

        if (getLoaderManager().getLoader(HitchhikeConstants.LOADER_ID_PASSENGER_RUNNING) == null) {
            getLoaderManager().initLoader(HitchhikeConstants.LOADER_ID_PASSENGER_RUNNING, null, loaderCallbacks);
        } else {
            getLoaderManager().restartLoader(HitchhikeConstants.LOADER_ID_PASSENGER_RUNNING, null, loaderCallbacks);
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if ((mAdapter != null && mAdapter.getItemCount() == 0) || currPage == 0) {
            requestData();
        }
        setupButtons();
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onRefresh() {
        currPage = 0;
        requestData();
    }

    @Override
    public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
        currPage += 1;
        requestData();
    }

    public void onEventMainThread(final HitchhikePassengerTripPayEvent event){
        startActivity(PassengerTripDetailActivity.newIntent(event.getTicket()));
    }

    private void setupButtons() {
        if (mAdapter != null) {
            int drawableId;
            if (mAdapter.getItemCount() == 0) {
                drawableId = R.drawable.button_background;
                btnNewTrip.setClickable(true);
            } else {
                drawableId = R.drawable.button_background_disabled;
                btnNewTrip.setClickable(false);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                btnNewTrip.setBackground(getResources().getDrawable(drawableId));
            } else {
                btnNewTrip.setBackgroundDrawable(getResources().getDrawable(drawableId));
            }
        }
    }

    private void requestData() {
        HitchhikeNetworkHelper.INSTANCE.getPassengerUnfinishedTickets(currPage, 10, new OnGetTicketsListener() {
            @Override
            public void onSuccess(ArrayList<TicketModel> items) {
                if (currPage == 0) {
                    mLinearLayoutManager.scrollToPosition(0);
                    listView.setRefreshing(false);
                } else {
                    listView.setLoadingMore(false);
                }
                if (currPage > 0){
                    currPage -= 1;
                }
                getLoaderManager().restartLoader(HitchhikeConstants.LOADER_ID_PASSENGER_RUNNING, null, loaderCallbacks);
                setupButtons();
            }

            @Override
            public void onFailure(Throwable throwable) {
                if (currPage == 0) {
                    listView.setRefreshing(false);
                } else {
                    listView.setLoadingMore(false);
                }
                if (currPage > 0){
                    currPage -= 1;
                }
                ToastUtils.show(GlobalContext.getGlobalContext(), com.sita.tboard.util.TextUtils.getThrowableMessage(throwable));
            }
        });
    }

    @OnClick(R.id.btn_new_trip)
    void onClickBtnNewTripPlan() {
        startActivity(PassengerPublishTripActivity.newIntent());
    }

    @OnClick(R.id.btn_history)
    void onClickBtnHistory() {
        startActivity(PassengerHistoryTicketsActivity.newIntent());
    }
}
